<?php

	class OauthLogin {

		private $_currentUser = false;
		private $_authenticated = false;

		private $_googleClient = false;
		private $_googleOauthService = false;
		private $_googleUserProfile = false;

		private $_twitterOauthService = false;
		private $_twitterAccessToken = false;
		private $_twitterUserProfile = false;

		private $_facebookOauthService = false;
		private $_facebookUserProfile = false;
		private $_facebookUserFriends = false;

		private $_linkedinOauthService = false;
		private $_linkedinUserProfile = false;
		private $_linkedinUserFriends = false;

		function __construct( $service = 'google' ) {
			$this->_service = $service;
			if( $this->_service === 'google' ) {
				$this->_googleClient = new Google_Client();
				$this->_googleClient->setClientId( GOOGLE_CLIENT_ID );
				$this->_googleClient->setClientSecret( GOOGLE_CLIENT_SECRET );
				$this->_googleClient->setDeveloperKey( GOOGLE_DEVELOPER_KEY );
				$this->_googleClient->setRedirectUri( HOME_PATH . 'google-oauth-callback/' );
				$this->_googleOauthService = new Google_Oauth2Service( $this->_googleClient );
				if( isset( $_GET[ 'code' ] ) ) {
					try {
						$youtube = new Google_YoutubeService( $this->_googleClient );
						$this->_googleClient->authenticate();
						$this->_googleUserProfile = $this->_googleOauthService->userinfo->get();
						$channelsResponse = $youtube->channels->listChannels( 'snippet,contentDetails,statistics,status', array(
							'mine' => 'true',
						));
						$this->_googleUserProfile[ 'access_token' ] = json_decode( $this->_googleClient->getAccessToken(), true );
						$this->_googleUserProfile[ 'channels' ] = $channelsResponse;
						$_SESSION[ 'google_user_profile' ] = serialize( $this->_googleUserProfile );
						header( 'Location: /' );exit;
						$this->_authenticated = true;
					} catch( Exception $ex ) {
						describe( $ex->getMessage(), $ex->getTraceAsString(), true );
					}
				}
				if( $this->_googleUserProfile ) {
					$this->_getCurrentUser();
				}
			} else if( $this->_service === 'twitter' ) {
				$this->_twitterOauthService = new Twitter_Client( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, @$_SESSION[ 'oauth_token' ], @$_SESSION['oauth_token_secret' ] );
				if( !empty( $_GET[ 'oauth_token' ] ) && !empty( $_GET[ 'oauth_verifier' ] ) && !empty( $_SESSION[ 'oauth_token' ] ) && !empty( $_SESSION[ 'oauth_token_secret' ] ) ) {
					$_SESSION[ 'access_token' ] = $this->_twitterOauthService->getAccessToken( $_GET[ 'oauth_verifier' ] );
					$this->_twitterUserProfile = $this->_twitterOauthService->get( 'account/verify_credentials' );
					if( !empty( $this->_twitterUserProfile ) && isset( $this->_twitterUserProfile[ 'id' ] ) ) {
						$this->_authenticated = true;
					}
				}
				if( $this->_authenticated ) {
					$this->_getCurrentUser();
				}
			} else if( $this->_service === 'facebook' ) {
				$this->_facebookOauthService = new Facebook_Client( array(
					'appId'  => FACEBOOK_APP_ID,
					'secret' => FACEBOOK_APP_SECRET
				));
				$this->_facebookUserProfile = $this->_facebookOauthService->getUserProfile();
				if( !empty( $this->_facebookUserProfile ) ) {
					$this->_facebookUserFriends = $this->_facebookOauthService->getUserFriends();
					$this->_authenticated = true;
					$this->_getCurrentUser();
				}
			} else if( $this->_service === 'linkedin' ) {
				$this->_linkedinOauthService = new LinkedIn_LinkedIn( LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET );

				if( isset( $_GET[ 'oauth_token' ] ) && isset( $_GET[ 'oauth_verifier' ] ) ){
					$_SESSION[ 'oauth_verifier' ] = $_GET[ 'oauth_verifier' ];

					$this->_linkedinOauthService->request_token = unserialize( $_SESSION[ 'requestToken' ] );
					$this->_linkedinOauthService->oauth_verifier = $_SESSION[ 'oauth_verifier' ];
					$this->_linkedinOauthService->getAccessToken( $_GET[ 'oauth_verifier' ] );

					$_SESSION[ 'oauth_access_token' ] = serialize( $this->_linkedinOauthService->access_token );

					$xml_response = $this->_linkedinOauthService->getProfile( "~:(id,first-name,last-name,headline,picture-urls::(original),email-address)" );
					$this->_linkedinUserProfile = @json_decode( @json_encode(simplexml_load_string( $xml_response ) ), 1 );

					$search_response = $this->_linkedinOauthService->searchConnections();
					$this->_linkedinUserFriends = @json_decode( @json_encode(simplexml_load_string( $search_response ) ), 1 );

					$this->_authenticated = true;
					$this->_getCurrentUser();
				}
			}
		}

		public function _getUserFbFriends() {
			return $this->_facebookUserFriends;
		}

		public function _getUserLinkedinFriends() {
			return $this->_linkedinUserFriends;
		}

		private function _getCurrentUser() {
			if( $this->_service == 'google' ) {
				$users = getMultiple( 'user', 'email||' . $this->_googleUserProfile[ 'email' ] );
				if( $users->getResultCount() > 0 ) {
					$this->_currentUser = $users->get( 0 );
					$this->_currentUser->update( 'googleId||' . $this->_googleUserProfile[ 'id' ] );
					$googleUser = getSingle( 'userGoogle', $this->_googleUserProfile[ 'id' ] );
					if( $googleUser->getResultCount() > 0 ) {
						$googleUser->update( 'data||' . serialize( $this->_googleUserProfile ) );
					} else {
						getDb( 'userGoogle', 'add' )->set( 'userGoogleId||' . $this->_googleUserProfile[ 'id' ], 
															'data||' . serialize( $this->_googleUserProfile ) );
					}
				} else {
					$users = getMultiple( 'user', 'googleId||' . $this->_googleUserProfile[ 'id' ] );
					if( $users->getResultCount() > 0 ) {
						$this->_currentUser = $users->get( 0 );
						$this->_currentUser->update( 'email||' . $this->_googleUserProfile[ 'email' ] );
					} else {
						$login = explode( '@', $this->_googleUserProfile[ 'email' ] );
						$login = $login[ 0 ];
						$login = Utility::getUserName( $login );
						/* $libImage = new ImageUtility( 'user/google' );
						$imageId = $libImage->uploadImageFromUrl( $this->_googleUserProfile[ 'picture' ], $login, false, false ); */
						
						$newUser = getDb( 'user', 'add' );
						$newUser->set(  'fullName||' . $this->_googleUserProfile[ 'name' ], 
										'email||' . $this->_googleUserProfile[ 'email' ], 
										'gender||' . ( $this->_googleUserProfile[ 'gender' ] == 'male' ? 'M' : 'F' ), 
										'login||' . $login, 'status||verified', 'userRoleId||6', 
										'password||' . md5( 'somepass' ), 'birthDate||' . $this->_googleUserProfile[ 'birthday' ] );
						$this->_currentUser = getSingle( 'user', $newUser->getLastInsertedId() );
						$googleUser = getSingle( 'userGoogle', $this->_googleUserProfile[ 'id' ] );
						if( $googleUser->getResultCount() > 0 ) {
							$googleUser->update( 'data||' . serialize( $this->_googleUserProfile ) );
						} else {
							getDb( 'userGoogle', 'add' )->set( 'userGoogleId||' . $this->_googleUserProfile[ 'id' ], 
																'data||' . serialize( $this->_googleUserProfile ) );
						}
					}
				}
			} else if( $this->_service == 'twitter' ) {
				$users = getMultiple( 'user', 'twitterId||' . $this->_twitterUserProfile[ 'id' ] );
				if( $users->getResultCount() > 0 ) {
					$this->_currentUser = $users->get( 0 );
				} else {
					$_SESSION[ 'newTwitterUserId' ] = $this->_twitterUserProfile[ 'id' ];
				}
				$twitterUser = getSingle( 'userTwitter', $this->_twitterUserProfile[ 'id' ] );
				if( $twitterUser->getResultCount() > 0 ) {
					$twitterUser->update( 'data||' . serialize( $this->_twitterUserProfile ) );
				} else {
					getDb( 'userTwitter', 'add' )->set( 'userTwitterId||' . $this->_twitterUserProfile[ 'id' ], 
															'data||' . serialize( $this->_twitterUserProfile ) );
				}
			} else if( $this->_service == 'facebook' ) {
				$users = getMultiple( 'user', 'email||' . $this->_facebookUserProfile[ 'email' ] );
				if( $users->getResultCount() > 0 ) {
					$this->_currentUser = $users->get( 0 );
					$this->_currentUser->update( 'facebookId||' . $this->_facebookUserProfile[ 'id' ] );
					$facebookUser = getSingle( 'userFacebook', $this->_facebookUserProfile[ 'id' ] );
					if( $facebookUser->getResultCount() > 0 ) {
						$facebookUser->update( 'data||' . serialize( $this->_facebookUserProfile ), 
												'friendData||' . serialize( $this->_facebookUserFriends ) );
					} else {
						getDb( 'userFacebook', 'add' )->set( 'userFacebookId||' . $this->_facebookUserProfile[ 'id' ], 
																'data||' . serialize( $this->_facebookUserProfile ), 
																'friendData||' . serialize( $this->_facebookUserFriends ) );
					}
				} else {
					$users = getMultiple( 'user', 'facebookId||' . $this->_facebookUserProfile[ 'id' ] );
					if( $users->getResultCount() > 0 ) {
						$this->_currentUser = $users->get( 0 );
						/**
						 * @todo Need to discuss with Raghu sir for next line.
						 */
						//$this->_currentUser->update( 'email||' . $this->_facebookUserProfile[ 'email' ] );
					} else {
						$login = explode( '@', $this->_facebookUserProfile[ 'email' ] );
						$login = $login[ 0 ];
						$login = Utility::getUserName( $login );
						$newUser = getDb( 'user', 'add' );
						$birthdate = explode( '/', $this->_facebookUserProfile[ 'birthday' ] );
						$birthDate = "{$birthdate[2]}-{$birthdate[0]}-{$birthdate[1]}";
						$newUser->set( 'login||' . $login, 'fullName||' . $this->_facebookUserProfile[ 'name' ], 
							'email||' . $this->_facebookUserProfile[ 'email' ], 'status||verified', 'userRoleId||6', 
							'gender||' . ( $this->_facebookUserProfile[ 'gender' ] == 'male' ? 'M' : 'F' ), 
							'password||' . md5( 'somepass' ), 'birthDate||' . $birthDate );
						$this->_currentUser = getSingle( 'user', $newUser->getLastInsertedId() );
						$facebookUser = getSingle( 'userFacebook', $this->_facebookUserProfile[ 'id' ] );
						if( $facebookUser->getResultCount() > 0 ) {
							$facebookUser->update( 'data||' . serialize( $this->_facebookUserProfile ), 
													'friendData||' . serialize( $this->_facebookUserFriends ) );
						} else {
							getDb( 'userFacebook', 'add' )->set( 'userFacebookId||' . $this->_facebookUserProfile[ 'id' ], 
								'data||'.serialize($this->_facebookUserProfile),'friendData||'.serialize( $this->_facebookUserFriends));
						}
					}
				}
			}
			else if( $this->_service == 'linkedin' ) {
				$usersObj = getMultiple( 'user', 'email||' . $this->_linkedinUserProfile[ 'email-address' ] );
				if( $usersObj->getResultCount() > 0 ) {
					$this->_currentUser = $usersObj->get( 0 );
					$this->_currentUser->update( 'linkedinId||' . $this->_linkedinUserProfile[ 'id' ] );
					$linkedinUserObj = getSingle( 'userLinkedin', $this->_linkedinUserProfile[ 'id' ] );
					if( $linkedinUserObj->getResultCount() > 0 ) {
						$linkedinUserObj->update( 'data||' . serialize( $this->_linkedinUserProfile ), 
												'friendData||' . serialize( $this->_linkedinUserFriends ) );
					} else {
						getDb( 'userLinkedin', 'add' )->set( 'userLinkedinId||' . $this->_linkedinUserProfile[ 'id' ], 
							'data||'.serialize($this->_linkedinUserProfile),'friendData||'.serialize( $this->_linkedinUserFriends));
					}
				} else {
					$usersObj = getMultiple( 'user', 'linkedinId||' . $this->_linkedinUserProfile[ 'id' ] );
					if( $usersObj->getResultCount() > 0 ) {
						$this->_currentUser = $usersObj->get( 0 );
						/**
						 * @todo Need to discuss with Raghu sir for next line.
						 */
						//$this->_currentUser->update( 'email||' . $this->_linkedinUserProfile[ 'email' ] );
					} else {
						$login = explode( '@', $this->_linkedinUserProfile[ 'email-address' ] );
						$login = $login[ 0 ];
						$login = Utility::getUserName( $login );
						$newUserObj = getDb( 'user', 'add' );
						$fullName = $this->_linkedinUserProfile[ 'first-name' ] . ' ' . $this->_linkedinUserProfile[ 'last-name' ];
						$newUserObj->set( 'login||' . $login, 'fullName||' . $fullName, 
							'email||' . $this->_linkedinUserProfile[ 'email-address' ], 'status||verified', 'userRoleId||6',
							'password||' . md5( 'somepass' ) );

						$this->_currentUser = getSingle( 'user', $newUserObj->getLastInsertedId() );

						$linkedinUserObj = getSingle( 'userLinkedin', $this->_linkedinUserProfile[ 'id' ] );
						if( $linkedinUserObj->getResultCount() > 0 ) {
							$linkedinUserObj->update( 'data||' . serialize( $this->_linkedinUserProfile ), 
													'friendData||' . serialize( $this->_linkedinUserFriends ) );
						} else {
							getDb( 'userLinkedin', 'add' )->set( 'userLinkedinId||' . $this->_linkedinUserProfile[ 'id' ], 
								'data||'.serialize($this->_linkedinUserProfile),'friendData||'.serialize($this->_linkedinUserFriends));
						}
					}
				}
			}
		}

		function getAuthUrl() {
			if( $this->_service == 'google' ) {
				return $this->_googleClient->createAuthUrl();
			} else if( $this->_service == 'twitter' ) {
				$requestToken = $this->_twitterOauthService->getRequestToken( HOME_PATH . 'twitter-oauth-callback/' );
				$_SESSION[ 'oauth_token' ] = @$requestToken[ 'oauth_token'];
				$_SESSION[ 'oauth_token_secret' ] = @$requestToken['oauth_token_secret'];
				if( $this->_twitterOauthService->http_code == 200 ) {
					return $this->_twitterOauthService->getAuthorizeURL( $requestToken[ 'oauth_token'] );
				}
			} else if( $this->_service == 'facebook' ) {
				return $this->_facebookOauthService->getLoginUrl();			
			} else if( $this->_service == 'linkedin' ) {				
				$this->_linkedinOauthService->getRequestToken();
				$_SESSION['requestToken'] = serialize( $this->_linkedinOauthService->request_token );
				return $this->_linkedinOauthService->generateAuthorizeUrl();
			}
			return 'javascript:;';
		}

		function getCurrentUser() {
			return $this->_currentUser;
		}

		function getAuthenticated() {
			return $this->_authenticated;
		}
	}